<?php

namespace Mlym\CodeGeneration\InitGeneration\Controller\Method;

use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\Message\Status;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use Mlym\CodeGeneration\ClassGeneration\MethodAbstract;

class OnException extends MethodAbstract
{

    function addMethodBody()
    {
        $this->classGeneration->getPhpNamespace()->addUse(ParamValidateError::class);
        $this->classGeneration->getPhpNamespace()->addUse(Status::class);
        $this->classGeneration->getPhpNamespace()->addUse(Trigger::class);
        $method = $this->method;
        $method->addParameter('throwable')->setType(\Throwable::class);
        $method->setReturnType('void');
        $method->setBody(<<<BODY
if (\$throwable instanceof ParamValidateError) {
    \$this->writeJson(Status::CODE_BAD_REQUEST,[], \$throwable->getValidate()->getError()->__toString());
}  else {
    Trigger::getInstance()->throwable(\$throwable);
    \$this->writeJson(Status::CODE_INTERNAL_SERVER_ERROR, null, \$throwable->getMessage());
}
BODY
        );
    }

    function getMethodName(): string
    {
        return 'onException';
    }

    public function addComment()
    {
        $comment = <<<COMMENT
异常处理
@param \Throwable \$throwable 异常对象
@throws \Throwable
COMMENT;
        $this->method->addComment($comment);
    }
}